<template>
  <div class="module-card">
    <div class="module-header">
      <h2 class="module-title">{{ title }}</h2>
      <div class="text-sm text-gray-500">按完成后金额</div>
    </div>
    <div class="p-4">
      <div class="h-64" ref="resourceUsageChart"></div>
    </div>
  </div>
</template>

<script>

import * as echarts from "echarts";
// import { getEntityZhu } from "@/api/home/home";


export default {
  data() {
    return {
      title: "平台成交额排行",
      resourceChart: null,
      resourceData: []
    };
  },
  mounted() {
    const userType = this.$store.getters.userType;
    if (userType === '03') {
      this.title = "企业收入排行";
    } else {
      this.title = "企业支出排行";
    }

    this.getData()
    this.resourceChart = echarts.init(this.$refs.resourceUsageChart);
    // this.initResourceChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (this.resourceChart) {
      this.resourceChart.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    getData() {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth(); // 月份从0开始（0=1月，11=12月）

      // 当月第一天
      const startDate = new Date(year, month, 1);
      // 当月最后一天（下月第一天减1天）
      const endDate = new Date(year, month + 1, 0);

      // 格式化为 "YYYY-MM-DD"
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      // console.log("获取成交额排行数据");
      // 调用接口时可根据实际需求动态设置日期范围
      getEntityZhu({
        startDate: formatDate(startDate),
        endDate: formatDate(endDate)
      }).then(res => {
        const key = Object.keys(res.data);
        // console.log("接口返回原始数据:", res.data, key);
        if (res.data && key.length) {
          // 根据用户类型处理数据
          // 将对象转换为数组并处理字段
          this.resourceData = Object.entries(res.data).map(([name, entityData]) => {
            let usage = 0;
            const userType = this.$store.getters.userType;

            // 区分用户类型取不同字段作为usage
            if (userType === '03') {
              // 03类型用户使用totalIncome作为usage
              usage = Number(entityData.totalIncome) || 0;
            } else{
              // 02类型用户使用totalExpense作为usage
              usage = Number(entityData.totalExpense) || 0;
            }
            return { name, usage };
          })
            // 按usage降序排序（取前6名，保持与示例格式一致）
            .sort((a, b) => b.usage - a.usage)
            .slice(0, 6);

          // console.log("组装图-图表数据:", this.resourceData);
          // 数据更新后重新渲染图表
          this.initResourceChart();
        } else {
          this.resourceData = [
            { name: '暂无数据', usage: 0 }
          ];
          // console.log("组装图-图表数据:", this.resourceData);
          this.initResourceChart();
        }
      }).catch(err => {
        console.error("获取数据失败:", err);
        // 错误处理：可设置默认数据避免图表空白
        this.resourceData = [
          { name: '暂无数据', usage: 0 }
        ];
        this.initResourceChart();
      });
    },
    handleResize() {
      this.resourceChart?.resize();
    },
    initResourceChart() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: '{b}: ¥{c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          max: this.resourceData[0].usage,// 使用排名第一的数值为max
          axisLabel: { formatter: '¥{value}' }
        },
        yAxis: {
          type: 'category',
          data: this.resourceData.map(item => item.name),
          inverse: true
        },
        series: [
          {
            name: this.title,
            type: 'bar',
            data: this.resourceData.map(item => item.usage),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#3b82f6' },
                { offset: 1, color: '#60a5fa' }
              ])
            },
            barWidth: 16
          }
        ]
      };
      this.resourceChart.setOption(option);
    }
  }
};
</script>

<style scoped>
/* 保持与原页面一致的样式 */
.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid #f3f4f6;
}

.module-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1f2937;
}
</style>